<template>
  <div class="user-role">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="addRole">新增角色</el-button>
            <el-button @click="exportRoles">导出角色</el-button>
          </div>
        </div>
      </template>
      
      <!-- 角色列表 -->
      <el-table 
        :data="roleList" 
        border 
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="角色ID" width="80" />
        <el-table-column prop="name" label="角色名称" width="150" />
        <el-table-column prop="description" label="角色描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="userCount" label="用户数量" width="100">
          <template #default="scope">
            <el-tag type="success">{{ scope.row.userCount }}人</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
              {{ scope.row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button 
              type="text" 
              size="small" 
              @click="viewRole(scope.row)"
            >
              查看
            </el-button>
            <el-button 
              type="text" 
              size="small" 
              @click="editRole(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              type="text" 
              size="small" 
              @click="toggleStatus(scope.row)"
              :style="{ color: scope.row.status === 'active' ? '#f56c6c' : '#67c23a' }"
            >
              {{ scope.row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              type="text" 
              size="small" 
              @click="deleteRole(scope.row)"
              style="color: #f56c6c"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 新增/编辑角色对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      :title="roleDialogTitle"
      width="600px"
      @close="resetRoleForm"
    >
      <el-form :model="roleForm" :rules="roleRules" ref="roleFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="角色状态" prop="status">
          <el-radio-group v-model="roleForm.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRoleForm" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 角色详情对话框 -->
    <el-dialog
      v-model="roleDetailVisible"
      title="角色详情"
      width="600px"
    >
      <div v-if="currentRole" class="role-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="角色名称">
            {{ currentRole.name }}
          </el-descriptions-item>
          <el-descriptions-item label="角色状态">
            <el-tag :type="currentRole.status === 'active' ? 'success' : 'danger'">
              {{ currentRole.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="用户数量">
            <el-tag type="info">{{ currentRole.userCount }}人</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ currentRole.createTime }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ currentRole.updateTime }}
          </el-descriptions-item>
          <el-descriptions-item label="角色描述" :span="2">
            {{ currentRole.description || '暂无描述' }}
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 权限列表 -->
        <div class="permission-section">
          <h4>权限列表</h4>
          <el-tag 
            v-for="permission in currentRole.permissions" 
            :key="permission.id"
            class="permission-tag"
            type="info"
          >
            {{ permission.name }}
          </el-tag>
        </div>
        
        <!-- 用户列表 -->
        <div class="user-section">
          <h4>关联用户</h4>
          <el-table :data="currentRole.users || []" size="small">
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="realName" label="真实姓名" />
            <el-table-column prop="department" label="部门" />
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'" size="small">
                  {{ scope.row.status === 'active' ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { roleApi, userApi } from '@/api'

const loading = ref(true)
const roleDialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const submitting = ref(false)
const isEdit = ref(false)

interface Role {
  id: number;
  name: string;
  description: string;
  status: string;
  userCount: number;
  createTime: string;
  updateTime?: string;
  permissions: any[];
  users?: any[];
}

const currentRole = ref<Role | null>(null)
const roleFormRef = ref<FormInstance>()
const permissionTreeRef = ref()
const roleDetailVisible = ref(false)

// 角色表单
const roleForm = reactive({
  id: '',
  name: '',
  description: '',
  status: 'active'
})

// 角色表单验证规则
const roleRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '角色名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述长度不能超过 200 个字符', trigger: 'blur' }
  ]
}

// 分页
const pagination = ref({
  current: 1,
  size: 20,
  total: 0
})

// 角色列表
const roleList = ref<Role[]>([])

const loadData = async () => {
  loading.value = true
  try {
    const res:any = await roleApi.getList({
      page: pagination.value.current,
      size: pagination.value.size
    })
    const rows = res.list || res.records || []
    roleList.value = rows.map((r:any)=>({
      ...r,
      status: r.status === 1 ? 'active' : 'inactive',
      permissions: [],
      createTime: r.createdAt ? r.createdAt.replace('T',' ').split('.')[0] : '-'
    }))
    // 获取所有用户用于统计
    const users:any[] = await userApi.getAll()
    const roleCountByName: Record<string, number> = {}
    users.forEach((u:any)=>{
      if (!u.roleNames) return
      u.roleNames.split(',').forEach((rn:string)=>{
        const key = rn.trim()
        if (key) roleCountByName[key] = (roleCountByName[key]||0)+1
      })
    })
    roleList.value.forEach(r=>{r.userCount = roleCountByName[r.name] || 0})
    pagination.value.total = res.total || 0
  } finally {
    loading.value = false
  }
}

const handleSizeChange = (size:number)=>{
  pagination.value.size=size;
  loadData();
}
const handleCurrentChange=(cur:number)=>{
  pagination.value.current=cur;
  loadData();
}

// 权限树数据
const permissionTree = ref([
  {
    id: 'dashboard',
    label: '仪表盘',
    children: [
      { id: 'dashboard:view', label: '查看仪表盘' }
    ]
  },
  {
    id: 'asset',
    label: '资产管理',
    children: [
      { id: 'asset:view', label: '查看资产' },
      { id: 'asset:add', label: '添加资产' },
      { id: 'asset:edit', label: '编辑资产' },
      { id: 'asset:delete', label: '删除资产' },
      { id: 'asset:import', label: '导入资产' },
      { id: 'asset:export', label: '导出资产' }
    ]
  },
  {
    id: 'category',
    label: '分类管理',
    children: [
      { id: 'category:view', label: '查看分类' },
      { id: 'category:add', label: '添加分类' },
      { id: 'category:edit', label: '编辑分类' },
      { id: 'category:delete', label: '删除分类' }
    ]
  },
  {
    id: 'maintenance',
    label: '维护管理',
    children: [
      { id: 'maintenance:view', label: '查看维护' },
      { id: 'maintenance:add', label: '添加维护' },
      { id: 'maintenance:edit', label: '编辑维护' },
      { id: 'maintenance:delete', label: '删除维护' },
      { id: 'maintenance:schedule', label: '维护计划' }
    ]
  },
  {
    id: 'user',
    label: '用户管理',
    children: [
      { id: 'user:view', label: '查看用户' },
      { id: 'user:add', label: '添加用户' },
      { id: 'user:edit', label: '编辑用户' },
      { id: 'user:delete', label: '删除用户' },
      { id: 'user:role', label: '角色管理' }
    ]
  },
  {
    id: 'system',
    label: '系统设置',
    children: [
      { id: 'system:config', label: '系统配置' },
      { id: 'system:log', label: '操作日志' },
      { id: 'system:backup', label: '系统备份' }
    ]
  }
])

const permissionProps = {
  children: 'children',
  label: 'label'
}

const checkedPermissions = ref<string[]>([])
const expandedKeys = ref<string[]>(['dashboard', 'asset', 'category', 'maintenance', 'user', 'system'])

const roleDialogTitle = computed(() => isEdit.value ? '编辑角色' : '新增角色')

const addRole = () => {
  isEdit.value = false
  roleDialogVisible.value = true
}

const editRole = (row: any) => {
  isEdit.value = true
  Object.assign(roleForm, row)
  roleDialogVisible.value = true
}

const viewRole = (row: any) => {
  currentRole.value = row
  roleDetailVisible.value = true
}

const toggleStatus = async (row: Role) => {
  const action = row.status === 'active' ? '禁用' : '启用'
  try {
    await ElMessageBox.confirm(
      `确定要${action}角色"${row.name}"吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const newStatusValue = row.status === 'active' ? 0 : 1;
    await roleApi.updateStatus(row.id, newStatusValue);
    
    row.status = newStatusValue === 1 ? 'active' : 'inactive';
    ElMessage.success(`角色${action}成功`)
  } catch {
    // 用户取消
  }
}

const deleteRole = async (row: Role) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色"${row.name}"吗？删除后不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await roleApi.delete(row.id);
    roleList.value = roleList.value.filter(r => r.id !== row.id);
    ElMessage.success('删除成功');
  } catch {
    // 用户取消
  }
}

const exportRoles = () => {
  // 创建CSV内容
  const headers = ['角色ID', '角色名称', '角色描述', '状态', '用户数量', '创建时间']
  const csvContent = [
    headers.join(','),
    ...roleList.value.map(role => [
      role.id,
      role.name,
      role.description || '',
      role.status === 'active' ? '启用' : '禁用',
      role.userCount,
      role.createTime
    ].join(','))
  ].join('\n')
  
  // 创建下载链接
  const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)
  link.setAttribute('href', url)
  link.setAttribute('download', `角色列表_${new Date().toISOString().split('T')[0]}.csv`)
  link.style.visibility = 'hidden'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  
  ElMessage.success('角色列表导出成功')
}

const submitRoleForm = async () => {
  if (!roleFormRef.value) return
  
  try {
    await roleFormRef.value.validate()
    submitting.value = true
    
    const payload:any = {
      ...roleForm,
      status: roleForm.status === 'active' ? 1 : 0
    }

    if (isEdit.value) {
      await roleApi.update(Number(roleForm.id), payload)
      ElMessage.success('角色更新成功')
    } else {
      await roleApi.add(payload)
      ElMessage.success('角色创建成功')
      loadData()  // 重新拉取列表
    }
    
    roleDialogVisible.value = false
    resetRoleForm()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}

const resetRoleForm = () => {
  if (!roleFormRef.value) return
  roleFormRef.value.resetFields()
  Object.assign(roleForm, {
    id: '',
    name: '',
    description: '',
    status: 'active'
  })
}

const handleCreate = async (role: { name: string; description: string; status: string }) => {
  try {
    const res: any = await roleApi.add(role);
    const newRole = (res.data || res) as Role;
    roleList.value.push(newRole);
  } catch (err) {
    console.error('Failed to create role:', err);
  }
}

const handleDelete = async (roleId: number) => {
  try {
    await roleApi.delete(roleId);
    roleList.value = roleList.value.filter(role => role.id !== roleId);
  } catch (err) {
    console.error('Failed to delete role:', err);
  }
}

onMounted(()=>{
  loadData()
})
</script>

<style scoped>
.user-role {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.permission-tree {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

@media (max-width: 768px) {
  .user-role {
    padding: 10px;
  }
  
  .header-actions {
    flex-direction: column;
  }
}

.role-detail {
  padding: 20px;
}

.permission-section {
  margin-top: 20px;
}

.user-section {
  margin-top: 20px;
}

.permission-tag {
  margin-right: 5px;
}
</style> 